package cn.edu.hhu.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

/**
 * @anthor: lddd
 * @date: 2020/5/13 - 11:40
 * @description:
 **/
@WebFilter("/student/*")
public class StudentLoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //1获取请求资源的路径
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String requestURI = request.getRequestURI();
        System.out.println(requestURI);
        //2判断是否包含登陆相关资源路径
        if (requestURI.contains("index.jsp")||requestURI.contains("regist.jsp")||requestURI.contains("/studentLoginServlet")||requestURI.contains("/studentRegistServlet")||requestURI.contains("/css/")||requestURI.contains("/js/")||requestURI.contains("/fonts/")||requestURI.contains("/res/")){
            //包含，用户要登陆，放行
            chain.doFilter(req, resp);
        }
        else{
            //不包含，验证是否已登陆
            //Session中获取登陆信息
            Object loginStudent = request.getSession().getAttribute("loginStudent");
            if (loginStudent!= null){
                //若登录，放行
                chain.doFilter(req, resp);
            }
            else{
                //没有登陆，跳转到登录页面
                request.setAttribute("login_msg","您尚未登陆，请先登录！");
                System.out.println(request.getContextPath());
                request.getRequestDispatcher("/index.jsp").forward(request,response);
            }
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
